package com.smart.reader.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.smart.reader.common.Page;
import com.smart.reader.mapper.SysUserInfoMapper;
import com.smart.reader.exception.CustomException;
import com.smart.reader.model.bo.SysUserInfoAddBo;
import com.smart.reader.model.bo.SysUserInfoUpdateBo;
import com.smart.reader.model.po.SysUserInfo;
import com.smart.reader.model.vo.SysUserInfoVo;
import com.smart.reader.service.SysUserInfoService;
import javax.validation.Valid;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUserInfo> implements SysUserInfoService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(SysUserInfoAddBo sysUserInfo) throws CustomException {
        SysUserInfo userInfo = BeanUtil.copyProperties(sysUserInfo, SysUserInfo.class);
        Boolean save = this.save(userInfo);
        if (!save) {
            throw new CustomException("⽤户数据添加失败");
        }
        return Boolean.TRUE;
    }

    @Override
    public Page<SysUserInfoVo> queryInfo(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUserInfoVo> tableInfoVos = this.baseMapper.queryInfo();
        return new Page<>(pageNum, pageSize, tableInfoVos);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(Long id) throws CustomException {
        boolean remove = this.removeById(id);
        if (!remove) {
            throw new CustomException("⽤户数据删除失败");
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean edit(@Valid SysUserInfoUpdateBo sysUserInfo) throws CustomException { // 修复参数类型
        SysUserInfo userInfo = this.getById(sysUserInfo.getId());
        if (ObjectUtil.isEmpty(userInfo)) {
            throw new CustomException("用户数据不存在");
        }
        BeanUtil.copyProperties(sysUserInfo, userInfo); // 修复工具类名称
        boolean update = this.updateById(userInfo);
        if (!update) {
            throw new CustomException("用户数据修改失败");
        }
        return Boolean.TRUE;
    }

    @Override
    public SysUserInfoVo detail(Long id) {
        return this.baseMapper.detail(id);
    }
}